#!/usr/env/bin python
# -*- coding: utf-8 -*-

# @Time    : 2020-09-24 9:29 上午
# @Author  : yangdy
# @File    : 2020-09-24.501.二叉搜索树中的众数
# @Software: PyCharmCE
from tools.my_methods import *


# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution:
    def findMode(self, root: TreeNode) -> List[int]:
        if not root:
            return []
        nums = []

        def dfs(rt):
            if not rt:
                return
            dfs(rt.left)
            nums.append(rt.val)
            dfs(rt.right)

        dfs(root)
        ii, data = 0, []
        for i in range(1, len(nums)):
            if nums[i] != nums[i - 1]:
                data.append((nums[i - 1], i - ii))
                ii = i
        data.append((nums[-1], len(nums)-ii))
        data.sort(key=lambda x: x[1], reverse=True)
        ans = []
        for i in range(len(data)):
            if data[i][1] == data[0][1]:
                ans.append(data[i][0])
            else:
                break
        return ans


questions = [
    ([1, None, 2, 2],),
    ([2, None, 3, None, 4, None, 5, None, 6],),
    ([],)
]

work(questions, lambda q: Solution().findMode(mk_tree(q[0], TreeNode)))

